const jwt = require('jsonwebtoken');

const secret = 'jj_self';
const ErrorCode = require('./errorCode');
const BaseResp = require('./baseResp');
//  简易的生成token
exports.sign = data => jwt.sign({
  data,
  exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30)
}, secret);


exports.verify = () => {
  return function (req, res, next) {
    //  如果是登陆信息
    req.user = {};
    const token = req.headers.authorization;
    //  如果没有传入token直接判断未登陆
    if (!token) {
      return next(BaseResp.error(ErrorCode.TOKEN_ERROR));
    }

    try {
      const decoded = jwt.verify(token, secret);
      req.user = decoded.data;
      next();
    } catch (err) {
      return next(BaseResp.error(ErrorCode.TOKEN_ERROR));
    }
  }
};

exports.verifyHasToken = (req, res, next) => {
  return (req, res, next) => {
    req.user = {};
    const token = req.headers.authorization;
    //  如果没有传入token直接判断未登陆
    if (!token) {
      return next();
    }
    try {
      const decoded = jwt.verify(token, secret);
      req.user = decoded.data;
      next();
    } catch (err) {
      return next();
    }
  }
};
